package org.aceor.mddal.common.monitor;

import org.aceor.mddal.common.monitor.handler.MonitorPointHandler;

import java.util.concurrent.TimeUnit;

/**
 * 时间监控器
 * Created by lxue on 16/4/5.
 */
public class Monitor {
    private static ThreadLocal<String[]> sbThreadLocal = new ThreadLocal<String[]>();

    public static void start(MonitorPoint point, String[] params) {
        TimeMeter.getContext().begin(point);
        sbThreadLocal.set(params);
    }

    public static void startSqlExecuteMonitor(String... params) {
        start(MonitorPoint.EXECUTE_SQL, params);
    }

    public static void startConnectionGetMonitor(String dsKey) {
        start(MonitorPoint.GET_CONNECTION, new String[]{dsKey});
    }

    public static void startSqlParseMonitor(String sql) {
        start(MonitorPoint.PARSE_SQL, new String[]{sql});
    }

    public static void startMergeResultSetMonitor() {
        start(MonitorPoint.MERGE_RS, new String[0]);
    }

    public static void stop(MonitorPoint point) {
        stop(point, null);
    }

    public static void stop(MonitorPoint point, MonitorPointHandler handler) {
        long costTime = TimeMeter.getContext().getTimeSpan(point, TimeUnit.MICROSECONDS);
        String[] params = sbThreadLocal.get();
        MonitorPointExecutor.execute(point, costTime, params, handler);
    }
}
